package com.spring.lth.service.impl;

import com.spring.lth.domain.Card;
import com.spring.lth.domain.Person;
import com.spring.lth.domain.PersonAndCard;
import com.spring.lth.feign.CardService;
import com.spring.lth.mapper.PersonMapper;
import com.spring.lth.service.IPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author 罗天豪
 * @date 2019/7/26
 */
@Service
public class PersonServiceImpl implements IPersonService {
    @Autowired
    private CardService service;

    @Autowired
    private PersonMapper mapper;

    @Override
    public PersonAndCard getPersonById(Long id) {
        Person person = mapper.selectPersonById(id);
        Card cardById = service.getCardById(person.getPCardId());
        PersonAndCard personAndCard = new PersonAndCard(person,cardById);
        return personAndCard;
    }

    @Override
    public PersonAndCard savePerson(Person person) {
        Card card = new Card();
        String code = getCode();
        card.setCCode(code);

        Card card1 = service.saveCard(card);
        person.setPCardId(card1.getCId());
        int i = mapper.insertPerson(person);
        if (i==1) {
            PersonAndCard personAndCard = new PersonAndCard(person,card1);
            return personAndCard;
        }
        return null;
    }

    @Override
    public PersonAndCard removePerson(Person person) {
        mapper.deletePerson(person);
        Card cardById = service.getCardById(person.getPCardId());
        service.removeCard(cardById);
        PersonAndCard personAndCard = new PersonAndCard(person,cardById);
        return personAndCard;
    }

    public String getCode() {
        return UUID.randomUUID().toString().trim();
    }
}
